package com.smart.community.complaint.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.smart.community.commons.result.PageResult;
import com.smart.community.commons.result.Result;
import com.smart.community.complaint.dto.ComplaintDTO;
import com.smart.community.complaint.dto.ComplaintQueryDTO;
import com.smart.community.complaint.service.IComplaintService;
import com.smart.community.complaint.vo.ComplaintVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 投诉建议管理控制器
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-07-02
 */
@Slf4j
@RestController
@RequestMapping("/api/complaint")
@Tag(name = "投诉建议管理", description = "投诉提交、处理、回访、统计等功能")
@SaCheckLogin
public class ComplaintController {

    @Autowired
    private IComplaintService complaintService;

    // ========================= 投诉提交查询接口 =========================

    /**
     * 提交投诉建议
     * 
     * @param complaintDTO 投诉信息
     * @return 投诉ID
     */
    @PostMapping
    @Operation(summary = "提交投诉建议")
    public Result<Long> submitComplaint(@Valid @RequestBody ComplaintDTO complaintDTO) {
        try {
            Long complaintId = complaintService.submitComplaint(complaintDTO);
            return Result.success("提交成功", complaintId);
        } catch (Exception e) {
            log.error("提交投诉建议失败", e);
            return Result.fail("提交失败：" + e.getMessage());
        }
    }

    /**
     * 分页查询投诉建议
     * 
     * @param complaintQueryDTO 查询条件
     * @return 分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询投诉建议")
    public Result<PageResult<ComplaintVO>> pageComplaints(ComplaintQueryDTO complaintQueryDTO) {
        try {
            // 验证查询参数
            if (!complaintQueryDTO.isValid()) {
                return Result.fail("查询参数无效");
            }
            
            PageResult<ComplaintVO> result = complaintService.pageComplaints(complaintQueryDTO);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("分页查询投诉建议失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取投诉详情
     * 
     * @param complaintId 投诉ID
     * @return 投诉详情
     */
    @GetMapping("/{complaintId}")
    @Operation(summary = "获取投诉详情")
    public Result<ComplaintVO> getComplaintDetail(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId) {
        try {
            ComplaintVO result = complaintService.getComplaintDetail(complaintId);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取投诉详情失败，投诉ID: {}", complaintId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户投诉列表
     * 
     * @param userId 用户ID
     * @return 投诉列表
     */
    @GetMapping("/user/{userId}")
    @Operation(summary = "获取用户投诉列表")
    public Result<List<ComplaintVO>> getUserComplaints(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            List<ComplaintVO> result = complaintService.getComplaintsByUserId(userId);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取用户投诉列表失败，用户ID: {}", userId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    // ========================= 投诉管理接口 =========================

    /**
     * 更新投诉信息
     * 
     * @param complaintId 投诉ID
     * @param complaintDTO 投诉信息
     * @return 更新结果
     */
    @PutMapping("/{complaintId}")
    @Operation(summary = "更新投诉信息")
    public Result<Boolean> updateComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Valid @RequestBody ComplaintDTO complaintDTO) {
        try {
            boolean result = complaintService.updateComplaint(complaintId, complaintDTO);
            return Result.success("更新成功", result);
        } catch (Exception e) {
            log.error("更新投诉信息失败，投诉ID: {}", complaintId, e);
            return Result.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除投诉记录
     * 
     * @param complaintId 投诉ID
     * @return 删除结果
     */
    @DeleteMapping("/{complaintId}")
    @Operation(summary = "删除投诉记录")
    public Result<Boolean> deleteComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId) {
        try {
            boolean result = complaintService.deleteComplaint(complaintId);
            return Result.success("删除成功", result);
        } catch (Exception e) {
            log.error("删除投诉记录失败，投诉ID: {}", complaintId, e);
            return Result.fail("删除失败：" + e.getMessage());
        }
    }

    // ========================= 投诉处理接口 =========================

    /**
     * 处理投诉
     * 
     * @param complaintId 投诉ID
     * @param complaintDTO 处理信息
     * @return 处理结果
     */
    @PostMapping("/{complaintId}/handle")
    @Operation(summary = "处理投诉")
    public Result<Boolean> handleComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Valid @RequestBody ComplaintDTO complaintDTO) {
        try {
            boolean result = complaintService.handleComplaint(complaintId, complaintDTO);
            return Result.success("处理成功", result);
        } catch (Exception e) {
            log.error("处理投诉失败，投诉ID: {}", complaintId, e);
            return Result.fail("处理失败：" + e.getMessage());
        }
    }

    /**
     * 分配投诉处理人
     * 
     * @param complaintId 投诉ID
     * @param handlerId 处理人ID
     * @return 分配结果
     */
    @PostMapping("/{complaintId}/assign")
    @Operation(summary = "分配投诉处理人")
    public Result<Boolean> assignComplaintHandler(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Parameter(description = "处理人ID") @RequestParam Long handlerId) {
        try {
            boolean result = complaintService.assignHandler(complaintId, handlerId);
            return Result.success("分配成功", result);
        } catch (Exception e) {
            log.error("分配投诉处理人失败，投诉ID: {}, 处理人ID: {}", complaintId, handlerId, e);
            return Result.fail("分配失败：" + e.getMessage());
        }
    }

    /**
     * 解决投诉
     * 
     * @param complaintId 投诉ID
     * @param solution 解决方案
     * @return 解决结果
     */
    @PostMapping("/{complaintId}/solve")
    @Operation(summary = "解决投诉")
    public Result<Boolean> solveComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Parameter(description = "解决方案") @RequestParam String solution) {
        try {
            boolean result = complaintService.solveComplaint(complaintId, solution);
            return Result.success("解决成功", result);
        } catch (Exception e) {
            log.error("解决投诉失败，投诉ID: {}", complaintId, e);
            return Result.fail("解决失败：" + e.getMessage());
        }
    }

    /**
     * 关闭投诉
     * 
     * @param complaintId 投诉ID
     * @param remark 关闭备注
     * @return 关闭结果
     */
    @PostMapping("/{complaintId}/close")
    @Operation(summary = "关闭投诉")
    public Result<Boolean> closeComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Parameter(description = "关闭备注") @RequestParam String remark) {
        try {
            boolean result = complaintService.closeComplaint(complaintId, remark);
            return Result.success("关闭成功", result);
        } catch (Exception e) {
            log.error("关闭投诉失败，投诉ID: {}", complaintId, e);
            return Result.fail("关闭失败：" + e.getMessage());
        }
    }

    /**
     * 投诉重开
     * 
     * @param complaintId 投诉ID
     * @param reason 重开原因
     * @return 重开结果
     */
    @PostMapping("/{complaintId}/reopen")
    @Operation(summary = "投诉重开")
    public Result<Boolean> reopenComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Parameter(description = "重开原因") @RequestParam String reason) {
        try {
            boolean result = complaintService.reopenComplaint(complaintId, reason);
            return Result.success("重开成功", result);
        } catch (Exception e) {
            log.error("投诉重开失败，投诉ID: {}", complaintId, e);
            return Result.fail("重开失败：" + e.getMessage());
        }
    }

    /**
     * 回访投诉
     * 
     * @param complaintId 投诉ID
     * @param satisfactionRate 满意度评分
     * @param followupResult 回访结果
     * @return 回访结果
     */
    @PostMapping("/{complaintId}/followup")
    @Operation(summary = "回访投诉")
    public Result<Boolean> followupComplaint(
            @Parameter(description = "投诉ID") @PathVariable Long complaintId,
            @Parameter(description = "满意度评分") @RequestParam Integer satisfactionRate,
            @Parameter(description = "回访结果") @RequestParam String followupResult) {
        try {
            boolean result = complaintService.followupComplaint(complaintId, satisfactionRate, followupResult);
            return Result.success("回访成功", result);
        } catch (Exception e) {
            log.error("回访投诉失败，投诉ID: {}", complaintId, e);
            return Result.fail("回访失败：" + e.getMessage());
        }
    }

    // ========================= 投诉统计接口 =========================

    /**
     * 获取投诉统计信息
     * 
     * @param communityId 社区ID
     * @return 统计信息
     */
    @GetMapping("/statistics")
    @Operation(summary = "获取投诉统计信息")
    public Result<Map<String, Object>> getComplaintStatistics(
            @Parameter(description = "社区ID") @RequestParam Long communityId) {
        try {
            Map<String, Object> result = complaintService.getComplaintStatistics(communityId);
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取投诉统计信息失败，社区ID: {}", communityId, e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取超时投诉列表
     * 
     * @return 超时投诉列表
     */
    @GetMapping("/timeout")
    @Operation(summary = "获取超时投诉列表")
    public Result<List<ComplaintVO>> getTimeoutComplaints() {
        try {
            List<ComplaintVO> result = complaintService.getTimeoutComplaints();
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取超时投诉列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 获取待回访投诉列表
     * 
     * @return 待回访投诉列表
     */
    @GetMapping("/pending-followup")
    @Operation(summary = "获取待回访投诉列表")
    public Result<List<ComplaintVO>> getPendingFollowupComplaints() {
        try {
            List<ComplaintVO> result = complaintService.getPendingFollowupComplaints();
            return Result.success("查询成功", result);
        } catch (Exception e) {
            log.error("获取待回访投诉列表失败", e);
            return Result.fail("查询失败：" + e.getMessage());
        }
    }

    /**
     * 清除投诉缓存
     * 
     * @param communityId 社区ID
     * @return 清除结果
     */
    @DeleteMapping("/cache/{communityId}")
    @Operation(summary = "清除投诉缓存")
    public Result<String> clearComplaintCache(
            @Parameter(description = "社区ID") @PathVariable Long communityId) {
        try {
            complaintService.clearComplaintCache(communityId);
            return Result.success("清除成功", "缓存已清除");
        } catch (Exception e) {
            log.error("清除投诉缓存失败，社区ID: {}", communityId, e);
            return Result.fail("清除失败：" + e.getMessage());
        }
    }
}
